/*
 * me2scrap
 *  - child of me2ools (me2day bookmarklet tools)
 *
 * Script enhancement for Me2Day
 *
 * Author:     Sean Yee <me2day.net/lethee>
 *             Mage <me2day.net/mage>
 *             The Weaveus Members.
 *
 * Date:       2009-06-09
 * LastUpdate: 2009-06-12
 * Version:    0.1 (no roadmap -_-)
 *
 * Repository: svn checkout http://me2scrap.googlecode.com/svn/trunk/ me2scrap-read-only
 * Site:       http://svn.weaveus.com/public/me2ool/bookmarklet.html
 *
 * Tested Under:
 *             Safari 4 (Mac)
 *             Firefox 3 (Mac)
 *
 */

//
// Code autoloaded by the bookmarklet
//
(function(){
//
// loading jQuery.
//
if (me2ool_isMe2daySite()) {
	if (!me2ool_isLoad()) {
		if (typeof jQuery == 'undefined') {
			include("http://hantor.net/~mage/me2scrap/jquery-1.3.2.min.js");
			log("[INIT] wait for libraries");
			me2ool_waitLibrary();
		}
		else {
			me2ool_load();
		}
	}
	else {
		log("[INIT] me2ool loaded already");
		me2ool_update();
		log("[UPDATE] scrap button loaded again");
	}
}

})();

function log(msg) {
	//
	// safari debug console or firefox's firebug console
	//
	if (window.console) {
		window.console.log(msg);
	}
}

//
// Wait for loading jquery script. Busy wait.
// Call me2ool_load() after that.
//
function me2ool_waitLibrary() {
	if (typeof jQuery == 'undefined' && typeof dateFormat == 'undefined' ) { 
		setTimeout(me2ool_waitLibrary,100);
	}
	else { 
		jQuery.noConflict();
		me2ool_load();
	}
}

//
// Initailize me2ool
//
function me2ool_load() {
	log("[me2ool_load] wait for load me2ool");
	
	//
	// It's a flag the me2ool is loaded already.
	//
	jQuery('body').append('<div id="me2ool_div"><div>');
	
	//
	// Modify style of post
	//
	/*
	jQuery('#container_contents div.post_cont > p').css('font-family', 'Daum');
	jQuery('#container_contents div.post_cont > p').css('font-size', '1.3em');
	jQuery('#container_contents div.post_cont > p').css('letter-spacing', '-2px');
	jQuery('#container_contents div.post_cont > p').css('word-spacing', '2px');
	*/
	
	//
	// Modify Sidebar Menu
	//
	//jQuery('#side_bar div.menu_navi li.mn_all > a').html('Our TimeLine');
	//jQuery('#side_bar div.menu_navi li.mn_me > a').html('Posts');
	//jQuery('#side_bar div.menu_navi li.mn_friends > a').html('Frnz');
	//jQuery('#side_bar div.menu_navi li.mn_comments > a').html('Comments');
	//jQuery('#side_bar div.menu_navi li.mn_mentioned > a').html('Mentioned');
	//jQuery('#side_bar div.menu_navi li.mn_sms > a').html('Recalls');
	//jQuery('#side_bar div.menu_navi li.mn_archive > a').html('Archives');
	
	//
	// Modify metoo button text
	//
	/*
	jQuery('#container_contents .post_section > .metoo_cnt > .me2button > a').each( function() { 
		jQuery(this).text('Me too!').css('font-size', '1.2em'); 
	} );
	*/

	me2ool_update();
	
	//me2ool_loadMe2oolMenu();
	//me2ool_design_hideNotify();
	//me2ool_catchEndOfDocument();
	
	log("[me2ool_load] me2ool loaded");
	log("[me2ool_load] entries: " + me2ool_getPageEntries().size());
	log("[me2ool_load] Page Info: " + me2ool_getPageType() + " of " + me2ool_getPageOwnerId());
}

//
// me2ool update. It must safe for multiful call without page reflash.
//
function me2ool_update() {

	jQuery('#container_contents .post_section > .post_cont').each( function() {
		if(jQuery(this).find('.scrap-button').size() > 0){
			jQuery(this).find('.scrap-button').remove();
		}
		jQuery(this).append("<a class=\"scrap-button\">[ 스크랩 ]</a>");

		var scrapbutton = jQuery(this).find('.scrap-button');
		var bookmark = "http://me2day.net" + jQuery(this).find('.timestamp a[rel="bookmark"]').attr("href");
		var content_clone = jQuery(this).find('p').clone();
		content_clone.find('span[class="timestamp"]').remove();
		var content_html = jQuery.trim( content_clone.html() );
		var content_text = jQuery.trim( content_clone.text() );
		var tagline_html = jQuery.trim( jQuery(this).find('.tagline .tag_edit_script_form').html() );
		var tagline_text = jQuery.trim( jQuery(this).find('.tagline .tag_edit_script_form').text() );

		scrapbutton.css("color", "#000");
		scrapbutton.css("font-size", "11px");
		scrapbutton.css("cursor", "pointer");
		scrapbutton.click( function(){
			(function(){f='http://delicious.com/save?url='+encodeURIComponent(bookmark)+'&tags=me2scrap'+'&notes='+encodeURIComponent(content_text + '\n(' +tagline_text + ')')+'&title='+encodeURIComponent("[me2day scrap] " + content_text)+'&v=5&';a=function(){if(!window.open(f+'noui=1&jump=doclose','deliciousuiv5','location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550'))location.href=f+'jump=yes'};if(/Firefox/.test(navigator.userAgent)){setTimeout(a,0)}else{a()}})();
		} );
	} );
}

function me2ool_design_hideNotify() {
	jQuery('#bgleft').css('visibility','hidden');
}

//
// Create a me2ool menu at the next of preference menu
//
function me2ool_loadMe2oolMenu() {
	jQuery("#topbar div.topMenu > ul > li:eq(3)").after('<li><a href="javascript:me2ool_openMenu()">+:미툴설정:+</a></li>');
}

//
// Open a me2ool panel
//
function me2ool_openMenu() {
	
}


//
// fetch json data of posts of friends
//
function me2ool_getFriendsPost() {
	var jsonUrl = 'http://me2day.net/api/get_posts/lethee.json?scope=friend[all]';
	jQuery.getJSON(jsonUrl)
}

//
// parse div.entry
// returned entry has only a attribute 'post_id'
//
function me2ool_parseEntry(entryElement) {
	var entry = new Object();
	
	var postid = entryElement.id;
	postid = postid.replace('post_','');
	postid = postid.replace('_container', '');
	entry.post_id = postid;
	
	return entry;
}

function me2ool_isMe2daySite() {
	return (document.location.href.substr(0, 18) == 'http://me2day.net/')
}

function me2ool_isLoad() {
	return (document.getElementById('me2ool_div') != null);
}

//
// If this value is false, then
// it's ready to load next page contents.
//
me2ool_flagForNextPageLoading = false;

//
// Load next contents when scroll are end of document.
//
function me2ool_catchEndOfDocument() {
	jQuery(window).scroll( function(i) {
		if (me2ool_flagForNextPageLoading)
			return;
		if (me2ool_isEndofDocument()) {
			log("[me2ool_catchEndOfDocument]");
			me2ool_flagForNextPageLoading = true;
			
			//
			// me2ool_loadNextContents() function
			// must set 'me2ool_flagForNextPageLoading' to 'false'
			// to load next page continuously when scroll is reached up to end.
			//
			me2ool_loadNextContents();
		}
	});
}

function me2ool_isloadingNextContents() {
	return false;
}

function me2ool_loadNextContents() {
	
	//
	// next page link
	//
	var appendingPageLinkTagSelector = "";
	switch(me2ool_getPageType()) {
		case "personal":
			appendingPageLinkTagSelector = "#prev_page_anchor";
			break;
		case "friends":
			appendingPageLinkTagSelector = "#next_page_anchor";
			break;
		default:
			return;
	}
	if (jQuery(appendingPageLinkTagSelector).size() == 0) {
		//
		// a next-page has no more contents.
		//
		return;
	}
	
	var nextPageUrl = jQuery(appendingPageLinkTagSelector).attr("href");
	log("[me2ool_loadNextContents] " + nextPageUrl);
	
	jQuery.get(nextPageUrl, function(result) {
		var resultDom = jQuery(result);
		
		var newDayContainers = me2ool_getDayContainers(jQuery('#wrapper', resultDom));
		if (newDayContainers.size() <= 0) {
			//
			// it's impossible.
			//
			log("[me2ool_loadNextContents] newDayContainers.size() must > 0 but " + newDayContainers.size());
			return;
		}
		
		//
		// remove duplicated 'day containers'
		//
		newDayContainers.each( function(idx, day) {
			var dayCtnSelector = '#wrapper #' + day.id;
			if(jQuery(dayCtnSelector).size() == 1) {				
				log("[me2ool_loadNextContents] remove duplicated contents. dayContainer id: " + day.id);
				day.remove();
			}
		});
		
		//
		// append 'day conatiners' to '#wrapper'
		//
		var dayContainers = jQuery("#wrapper .day", resultDom);
		dayContainers.appendTo( jQuery("#wrapper .day:last") );
		
		//
		// replace old next page link to new link.
		//
		var newNextUrl = jQuery(appendingPageLinkTagSelector, resultDom).attr("href");
		jQuery(appendingPageLinkTagSelector).attr("href", newNextUrl);
		delete resultDom;
		
		log("[me2ool_loadNextContents] entries: " + me2ool_getPageEntries().size());
		
		//
		// enable functionality to load next-page content after a while
		//
		setTimeout(me2ool_flagForNextPageLoading = false, 300);
	});
}

function me2ool_isEndofDocument() {
	var personalPageTolerant = 100;
	var friendsPageTolerant = 100;
	var scrollRemains = me2ool_getScrollRemains();
	
	switch (me2ool_getPageType()) {
		case "personal":
			return (scrollRemains <= personalPageTolerant);
		case "friends":
			return (scrollRemains <= friendsPageTolerant);
		default:
			return false;
	}
}

function me2ool_getScrollRemains() {
	var unvisibleDocumentHeight = jQuery(document).height() - jQuery(window).height();
	return unvisibleDocumentHeight - jQuery(window).scrollTop();
}

function include(filename) {
	var head = document.getElementsByTagName('head')[0];

	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';

	head.appendChild(script);
}

//
// Get jQuery Array of entries in current page.
//
function me2ool_getPageEntries() {
	return me2ool_getEntries(jQuery("#wrapper"));
}

//
// @parameter dom - dom element that might have '.day' dom elements.
//
function me2ool_getDayContainers(dom) {
	return jQuery("> .day", dom)
}

//
// @parameter dom - dom element that might have '.entry' dom elements.
//
function me2ool_getEntries(dom) {
	return jQuery(".box_container .entry", dom);
}

//
// "personal", "friends"
//
function me2ool_getPageType() {
	var resourceUrl = window.location.pathname.substr(1);
	var urlArray = resourceUrl.split("/");
	if (urlArray.length == 1)
		return "personal";
	if (urlArray.length > 2) {
		if (urlArray[1] == "friends")
			return "friends";
	}
	return "";
}

function me2ool_getPageOwnerId() {
	var resourceUrl = window.location.pathname.substr(1);
	var urlArray = resourceUrl.split("/");
	return urlArray[0];
}

/*+------------------------------------------------------------------------+*/
/*| API Wrapper                                                            |*/
/*+------------------------------------------------------------------------+*/

//
// get entries in current page and parse
//
function me2ool_apiGetEntries() {
	jQuery("#fix_conts .box_container .entry").each( function(i){
		var entry = me2ool_parseEntry(this);
		var jsonUrl = 'http://me2day.net/api/get_posts.json?post_id=' + entry.post_id;
		jQuery.getJSON(jsonUrl, function(json) {
			//alert(json[0].post_id + ", " + json[0].pubDate + "\n" + json[0].body);
		});
	});
}
